package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 *
 * @author lyl
 * @created 2025/10/11 10:46
 * @description
 *
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    private static final String USER_LOGIN_URI = "/login";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("-----------过滤器执行了--------------");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String requestURI = req.getRequestURI();
        log.info("请求的URL:{}", requestURI);
        if(ObjectUtil.contains(requestURI, USER_LOGIN_URI)){
            log.info("用户登录请求:{}", requestURI);
            chain.doFilter(request, response);
            return;
        }
        String token = req.getHeader("token");
        if(ObjectUtil.isEmpty(token)){
            log.info("用户未登录,请先登录,token为不存在");
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            log.info("用户已登录,用户ID:{}", claims.get("id"));
            log.info("用户已登录,用户名:{}", claims.get("username"));
            chain.doFilter(request, response);
        }catch (Exception e){
            log.info("token解析失败");
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
